<template>
  <div class="process-list-container">
    <a-row class="operate-row mb-15">
      <a-col :span="6">{{ $t('other.processLists') }}
        <span @click="sortObj" v-if="!props.isView" class="process-list-sort" > <img src="../../../../assets/images/sortDes.png"  class="ml-4 w-14 " alt="#" /> 排序</span>
      </a-col>
      <a-col :span="18" class="text-right">
        <span v-if="props.isView">
          <a-space v-if="!isEnvLocal">
            <a-button type="primary" @click="exportExcels('base')">{{$t('common.outputExcel')}}</a-button>
            <a-button type="primary" @click="updateLibrary('base')">{{ $t('other.updateBaseProcess') }}</a-button>
            <a-button type="primary" @click="updateLibrary('style')">{{ $t('other.updateStyleProcess') }}</a-button>
          </a-space>
        </span>
        <a-space v-else>
          <a-button type="primary" ghost @click="()=> handleExportXls('/api/mo/mo-proc/export-template',  $t('other.pocessMode') )">{{$t('common.downMode')}}</a-button>
          <!--          <a-upload :file-list="fileList" name="file" :before-upload="beforeUpload" :headers="uploadHeadersToken" :show-upload-list="false" :action="uplaodUrl" @change="handleImportExcel">-->
          <a-upload name="file" :before-upload="beforeUpload" :headers="uploadHeadersToken" :show-upload-list="false" :action="uplaodUrl" @change="handleImportExcel">
            <a-button ghost type="primary">{{$t('common.importExcel')}}</a-button>
          </a-upload>
          <!-- <a-button type="warning" @click="onDelete" :disabled="disabledBtn">{{$t('common.delMore')}}</a-button> -->
          <a-button type="primary" @click="addProc('one')">{{ $t('other.addProcess') }}</a-button>
          <a-popconfirm :ok-text="$t('common.ok')" :cancel-text="$t('common.cancel')" @confirm="onPopConfirm" @cancel="onPopCancel">
            <template #icon> <span></span> </template>
            <template #title>
              <div class="pop-confirm-box">
                <div style="margin-left: -22px;">
                  {{ $t('other.pleaseInputAddNumber') }}：
                  <a-input-number :precision="0" v-model:value="addProceNo" placeholder="{{$t('other.pleaseInputAddNumber')}}" :min="1" :max="99" />
                </div>
              </div>
            </template>
            <a-button type="primary">{{ $t('other.batchAddition') }}</a-button>
          </a-popconfirm>
          <a-button type="primary" @click="addProc('more')">{{ $t('other.addFromProcess') }}</a-button>
        </a-space>
      </a-col>
    </a-row>


    <header>
      <!--<div>
        <a-checkbox :indeterminate="indeterminate" v-model:checked="checkedAll" :disabled="props.isView" @change="onCheckedAll"></a-checkbox>
      </div>-->
      <div class="fixed-width"  style="width: 24px;height: 24px; line-height: 16px; background: #3E8FF7;border-radius: 2px;padding: 4px 2px !important;margin-right: 10px; ">
        <span style=" font-weight: 400;color: #FFFFFF; margin: 0 -2px; "> {{ dataSource.length || 0 }} </span>
      </div>

      <div v-for="(item, index) in listHeaders" :key="index" :class="{'fixed-width': [ 0,1,2,3,4, 8].includes(index)}">
        <span class="text-red" v-if="![4, 7, 8].includes(index)"> *</span>{{item}}
      </div>
      <div class="fixed-width" v-if="!props.isView">{{$t('common.operate')}}</div>
    </header>
    <a-spin :spinning="props.loading">
      <a-form ref="listFormRef" :model="dataSource">
        <draggable :list="dataSource" is='draggable' filter=".unmover" :disabled="disabled || props.isView" handle=".can-sort-process" animation="300" :scroll="true" force-fallback="true" item-key="index" @sort="handleSort" @start="handleStart" class="drag-scroll-container">
          <template #item="{element, index}">
            <div :class="{'can-sort-process': index != 0}" style="min-height: 48px; display: flex; align-items: center;text-align: center;justify-content: space-between;">

              <div style=" margin-top: 11px;margin-right: 10px;">
                <div  class=" noneBg unmover" style=" width: 24px;height: 24px;background: #E7F1FF;border-radius: 2px; line-height: 16px; padding: 4px 2px !important; " v-if="element.status">
                  <span style="color:#3E8FF7;font-weight: 400;margin: 0 -2px; ">{{index +1 }}</span>
                </div>
                <div  class=" noneBg unmover" style=" width: 24px;height: 24px;background: #EAEAEA;border-radius: 2px; line-height: 16px;padding: 4px 2px !important;  " v-else>
                  <span style="color:#999999;font-weight: 400;margin: 0 -2px; ">{{index +1 }}</span>
                </div>
              </div>
              <div class="drag-process-list-box mt-12" style="width: 100%">
                <!--<div class="unmover">
                  <a-checkbox :disabled="(!index && !props.isView) || props.isView" v-model:checked="element.checked" @change="onCheckedOne"></a-checkbox>
                </div>-->
                <!--<div  class="fixed-width" ></div>-->
                <div  class="fixed-width" >
                  <a-form-item v-if="element.edit" :name="[index, 'section']" :rules="processRule.section">
                    <a-select :placeholder="$t('common.pleaseSelect')" v-model:value="element.section" min="0" allowClear>
                      <!-- <a-select-option v-for="item in sectionList" :key="item" :value="item.name">{{ item.name }}</a-select-option> -->
                      <!-- 当前版本只能选择“{{$t('components.dg')}}”一个t('basicData.section') -->
                      <a-select-option v-for="item in [$t('components.dg')]" :key="item" :value="item ">{{ item }}</a-select-option>
                    </a-select>
                  </a-form-item>
                  <span v-else>{{element.section}}</span>
                </div>
                <!--<div class="fixed-width">
                  <a-form-item v-if="element.edit && index" :name="[index, 'sortField']" :rules="processRule.sortField">
                    <a-input-number :placeholder="$t('common.pleaseInput')" v-model:value="element.sortField" :min="1" />
                  </a-form-item>
                  <span v-else>{{element.sortField}}</span>
                </div>-->
                <div class="fixed-width">
                  <a-form-item v-if="element.edit && !element.id " :name="[index, 'processNo']" :rules="processRule.processNo">
                    <a-input-number :placeholder="$t('common.pleaseInput')" :min="0" v-model:value="element.processNo" />
                  </a-form-item>
                  <span v-else>{{element.processNo}}</span>
                </div>

                <div  class="fixed-width">
                  <a-form-item v-if="element.edit" :name="[index, 'name']" :rules="processRule.name">
                    <a-input :placeholder="$t('common.pleaseInput')" v-model:value.trim="element.name" :maxLength="99" />
                  </a-form-item>
                  <a-tooltip v-else>
                    <template #title>{{element.name}}</template>
                    <span>{{element.name}}</span>
                  </a-tooltip>
                </div>

                <div class="fixed-width">
                  <a-form-item v-if="element.edit" :name="[index, 'processCode']" :rules="processRule.processCode">
                    <a-input :placeholder="$t('common.pleaseInput')" v-model:value.trim="element.processCode" :maxLength="29" />
                  </a-form-item>
                  <span v-else>{{element.processCode}}</span>
                </div>


                <div class="fixed-width unmover">
                  <a-form-item :name="[index, 'status']" >
                    <a-switch size="small" v-model:checked="element.status" :disabled="!element.edit"   />
                  </a-form-item>
                </div>


                <div>
                  <a-form-item v-if="element.edit" :name="[index, 'standardSeconds']" :rules="processRule.standardSeconds">
                    <a-input-number :placeholder="$t('common.pleaseInput')" v-model:value="element.standardSeconds" min="0" @change="emits('workTimeChange')" />
                  </a-form-item>
                  <span v-else>{{element.standardSeconds}}</span>
                </div>
                <div>
                  <a-form-item v-if="element.edit" :name="[index, 'labourCost']" :rules="processRule.labourCost">
                    <a-input-number :placeholder="$t('common.pleaseInput')" v-model:value="element.labourCost" min="0" @change="emits('priceChange')" />
                  </a-form-item>
                  <span v-else>{{element.labourCost}}</span>
                </div>
                <div>
                  <a-form-item v-if="element.edit" :name="[index, 'processGuide']">
                    <a-textarea :placeholder="$t('common.pleaseInput')" v-model:value.trim="element.processGuide" :maxLength="999" :rows="1" />
                  </a-form-item>
                  <a-tooltip v-else>
                    <template #title>{{element.processGuide}}</template>
                    <span>{{element.processGuide}}</span>
                  </a-tooltip>

                </div>
                <div class="fixed-width unmover">
                  <span class="code-link" v-if="element.edit" @click="operateImg(element,index, true)">{{$t('common.edit')}}</span>
                  <span class="code-link" v-else @click="operateImg(element,index)">
                    <span v-if="element.processPictureUrlList && element.processPictureUrlList.length">{{$t('common.look')}}</span>
                  </span>
                </div>
                <div class="fixed-width unmover" v-if="!props.isView">
                  <span v-if="element.edit">
                    <span class="code-link" @click="onSave(element, index)">{{$t('common.save')}}</span>
                    <a-divider type="vertical" />
                    <span class="code-link" @click="onCancel(element, index)">{{$t('common.cancel')}}</span>
                  </span>
                  <span v-else class="code-link" @click="onEditPro(element)">{{ $t('common.editor') }}</span>
                </div>
              </div>
            </div>

          </template>
        </draggable>
      </a-form>
    </a-spin>
    <CustomModal ref="customModalRef" @ok="onDeleteOk" />
    <ProcessModal ref="processModalRef" @ok="onAdd" />
    <UploadModal ref="uploadModalRef" @ok="onImgOk" />
  </div>
</template>
<script setup>
import ProcessModal from './processModal.vue'
import UploadModal from './uploadModal.vue'
import CustomModal from '@/components/confirmModal/customModal.vue'
import draggable from 'vuedraggable'
import { listHeaders, processRule } from './processConfig'
import { computed, ref, watch, onMounted, nextTick } from 'vue'
import { cloneDeep } from 'lodash'
import axios from "@/utils/request"
import { message } from 'ant-design-vue'
// import { store } from "@/store"
import { getBaseUrl, getToken, hasPermission } from "@/utils"
import i18n from '@/locales/index' 
const { t } = i18n.global
let emits = defineEmits(['workTimeChange', 'priceChange'])
let props = defineProps({
  loading: {
    type: Boolean,
    default: () => false,
    required: true
  },
  tableData: {
    type: Array,
    default: () => [],
    required: true
  },
  styleId: {
    default: () => '',
    required: true
  },
  processVersionId: {
    default: () => ''
  },
  isView: {
    default: () => false
  },
  moId: {
    default: () => ''
  }
})
let isEnvLocal = ref(process.env.VUE_APP_CONFIG == 'local')
let disabled = computed(() => dataSource.value.some(i => i.edit))
// let disabledBtn = computed(() => dataSource.value.every(i => !i.checked))
// let sectionList = computed(() => { return store.state.normalData.sectionList }) // 工段列表 
let listFormRef = ref()
let customModalRef = ref()
let processModalRef = ref()
let uploadModalRef = ref()
let dataSource = ref([])
let indeterminate = ref(false)
let checkedAll = ref(false)
let originList = ref([])
let originSortList = ref([])
let maxNum = ref(0)
let addProceNo = ref(1)
let uploadHeadersToken = {
  Authorization: getToken()
}
let uploadExcelReturnData = ref([]);
let uplaodUrl = `${getBaseUrl(process.env.NODE_ENV)}/api/mo/mo-proc/import-data`
const exportExcels = () => {
  let param = { id: props.processVersionId }
  axios.downFile('/api/mo/mo-proc/export-mo-process', param).then((data) => {
    if (!data) { return }
    if (typeof window.navigator.msSaveBlob !== 'undefined') {
      window.navigator.msSaveBlob(new Blob([data]), t('menu.mo:process')+'.xlsx')
    } else {
      let url = window.URL.createObjectURL(new Blob([data]))
      let link = document.createElement('a')
      link.style.display = 'none'
      link.href = url
      link.setAttribute('download', t('menu.mo:process')+'.xlsx')
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link) // 下载完成移除元素
      window.URL.revokeObjectURL(url) // 释放掉blob对象
    }
  })
}
const updateLibrary = async (type) => {
  let list = cloneDeep(dataSource.value);
  list.forEach(item => {
    item.id = null;
    item.styleId = props.styleId;
  })
  let url = type == 'base' ? '/api/mo/mo-proc/update-to-basic-process' : '/api/mo/mo-proc/update-to-style-process'
  const res = await axios.postAction(url, list)
  if (res.success) message.success(res.msg || t('common.doSuccess') )
}
/*const onDelete = async () => {
  let notOrigin = dataSource.value.filter(i => i.checked).every(i => !i.isOrigin)
  console.log("🚀 ~  ~ notOrigin^^^^^^^^^^", notOrigin)
  if (notOrigin) {
    initDelData()
    return
  }
  try {
    const res = await axios.getAction('/api/mo/mo-proc/get', { id: props.processVersionId })
    let { status, isScheduleBill } = res.data
    console.log('******', status, isScheduleBill);
    if (status == 0 && isScheduleBill == 0) {
      deleteInfo()
      return
    }
    let opts = {
      content: isScheduleBill == 0 ? t('other.delArtStationProcessBeDel') : t('other.delArtSchBeIngBeDel'),
      needOperate: isScheduleBill == 0,
      btnText: isScheduleBill == 0 ? t('common.del') : t('common.ok')
    }
    customModalRef.value.open(opts)
  } catch {
    console.log('err');
  }
}*/
const onDeleteOk = (value) => {
  if (value) deleteInfo()
}
const deleteInfo = async () => {
  let params = dataSource.value.filter(i => i.checked).map(i => i.id)
  const res = await axios.postAction('/api/mo/mo-proc/delete-detail', params)
  if (res.success) initDelData()
}
const initDelData = (updateTable = true) => {
  checkedAll.value = false
  indeterminate.value = false
  updateTable && (dataSource.value = dataSource.value.filter(i => !i.checked))
  emits('priceChange')
  emits('workTimeChange')
  initSortInfo()
}
const onPopConfirm = () => {
  Array.from(Array(addProceNo.value), (v, k) => k).forEach(() => {
    addProc('one')
  })
  nextTick(() => { addProceNo.value = 1 })
}
const onPopCancel = () => {
  addProceNo.value = 1
}
const addProc = (type) => {
  // console.log('------------', dataSource.value)
  initSortInfo()
  if (type == 'one') {
    let maxProcessNo = Number(Math.max(...(dataSource.value.map(i => i.processNo).filter(i => i >= 0)))) + 1
    const newProcess = {
      section: t('components.dg'),
      moId: props.moId,
      sortField: ++maxNum.value,
      processNo: maxProcessNo,
      processCode: maxProcessNo,
      standardSeconds: 0,
      labourCost: 0,
      statue: true,
      isAdd: true,
      edit: true,
      status: true
    }
    dataSource.value.push(newProcess)
    initSortInfo()
  } else {
    let selectedIds = dataSource.value.filter(i => i.originId).map(i => i.originId)
    processModalRef.value.open(props.styleId, selectedIds)
  }
}
const onAdd = (value) => {
  value.forEach(i => {
    i.sortField = ++maxNum.value
    i.originId = i.id
    delete i.id
    dataSource.value.push({ ...i })
  })
  emits('priceChange')
  emits('workTimeChange')
  initSortInfo()
}
const operateImg = (record, index, isEdit) => {
  uploadModalRef.value.open(record.processPictureUrlList, index, isEdit)
}
const onImgOk = (fileList, index) => {
  dataSource.value[index].processPictureUrlList = fileList
}
const onEditPro = (record) => {
  record.edit = true
  handleStart()
}
const onCancel = (record, index) => {
  if (record.isAdd) {
    dataSource.value.splice(index, 1)
    initSortInfo()
    record.edit = false
  } else {
    originList.value[index].edit = false
    dataSource.value = originList.value
  }
  initDelData(false)
}
const sortObj = () => {
  message.success('排序完成')
  dataSource.value.sort(function (a,b){
    return a.processNo-b.processNo
  })
}
const onSave = async (record, index) => {
  await listFormRef.value.validateFields()
  let list = cloneDeep(dataSource.value)
  list.splice(index, 1)
  let uniqueValue = list.some(i => (i.sortField == record.sortField) || (i.processNo == record.processNo) || (i.name == record.name) || (i.processCode == record.processCode))
  if (uniqueValue) {
    message.warning('工序号，工序名称，工序代码不唯一')
    return
  }
  record.edit = false
  record.isAdd = false
  initSortInfo()
  return true
}
/*const onCheckedAll = () => {
  dataSource.value.forEach((i, index) => {
    if (props.isView.value) {
      i.checked = checkedAll.value
    } else {
      index && (i.checked = checkedAll.value)
    }
  })
  indeterminate.value = false
}*/
/*const onCheckedOne = () => {
  let list = props.isView.value ? dataSource.value : cloneDeep(dataSource.value)
  !props.isView.value && list.shift()
  checkedAll.value = list.every(i => i.checked)
  if (checkedAll.value) {
    indeterminate.value = false
  } else {
    indeterminate.value = list.some(i => i.checked)
  }
}*/
const handleStart = () => {
  originList.value = cloneDeep(dataSource.value)
}
const handleSort = (e) => {
  if (e.newIndex == 0) {
    message.warning(t('other.firstCanNotSort'))
    dataSource.value = originList.value
  } else {
    dataSource.value.forEach((el, index) => {
      el.sortField = originSortList.value[index]
    })
  }
}
const initSortInfo = () => {
  originSortList.value = dataSource.value.map(i => i.sortField).filter(i => i > 0)
  maxNum.value = Math.max(...originSortList.value)
  // console.log("🚀 ~ file: processList.vue ~ line 287 ~ initSortInfo ~ maxNum.value ", maxNum.value)
}
const handleExportXls = (exportUrl, fileName, needParams = false) => {
  console.log(exportUrl, fileName, needParams)
  if (!fileName || typeof fileName != 'string') {
    fileName = '导出文件'
  }
  axios.downFile(exportUrl, needParams ? null : null).then((data) => {
    if (!data) {
      return
    }
    if (typeof window.navigator.msSaveBlob !== 'undefined') {
      window.navigator.msSaveBlob(new Blob([data]), fileName + '.xlsx')
    } else {
      let url = window.URL.createObjectURL(new Blob([data]))
      let link = document.createElement('a')
      link.style.display = 'none'
      link.href = url
      link.setAttribute('download', fileName + '.xlsx')
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link) // 下载完成移除元素
      window.URL.revokeObjectURL(url) // 释放掉blob对象
    }
  })
}
const beforeUpload = (file) => {
  const { name } = file
  // 校验是否是excel文件
  const isExcel = /(xls|xlsx)$/i.test(name)
  if (!isExcel) {
    message.error(t('other.onlyUploadFile'))
  }
  return isExcel
}
/* 导入 */
const handleImportExcel = (info) => {
  // axios.postAction('/api/mo/mo-proc/import-data`')
  // console.log(info)
  if (info.file.status !== 'uploading') {
    console.log('uploading')
  }
  if (info.file.status === 'done') {
    // console.log(info)
    if (info.file.response.success) {
      let uploadExcelReturnData1 = info.file.response.data;
      // console.log(uploadExcelReturnData1)
      uploadExcelReturnData1 && uploadExcelReturnData1.forEach(i => {
        i.sortField = ++maxNum.value
        i.originId = i.id
        i.status = i.status == 1
        delete i.id
        dataSource.value.push({ ...i })
      })
      emits('priceChange')
      emits('workTimeChange')
      initSortInfo()
      console.log(uploadExcelReturnData.value)
      // message.success(`${info.file.name} 文件上传成功`)
      // this.loadData()
    } else {
      message.error(info.file.response.msg)
    }
  } else if (info.file.status === 'error') {
    message.error(`${t('common.fileUploadErr')}: ${info.file.msg} `)
  }
}

watch(() => props.tableData, (newVal) => {
  // console.log('+^^^^^^^^^^^^newVal^^^', newVal)
  if (newVal) {
    dataSource.value = cloneDeep(newVal)
    dataSource.value.forEach(i => {
      i.isOrigin = true
      i.isAdd = false
      i.originId = i.id
      i.status =  i.status == 0 ? false : true
    })
    initSortInfo()
  }
}, { deep: true, immediate: true })

onMounted(async () => {
  // await store.dispatch("getSection")
})
defineExpose({
  hasPermission,
  dataSource,
  listFormRef
})
</script>
